from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView


from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from utils.constants import IMAGE_CODE_EXPIRE, SMS_CODE_EXPRIE
from verifications.serializers import VerificationSmsCodeSerializer

"""
图片验证码
请求路径:   /verifications/imagecodes/(?P<image_code_id>)/
视图函数:   APIView
"""
class VerificationImageAPIView(APIView):
    """
    当前端点击验证码或者是刷新页面的时候,就会发送ajax请求到后台,后台保存到redis当中,
    然后返回给前端
    请求参数:   image_code_id   类型uuid字符串
    通过第三方库生成图片验证码
    """
    def get(self, request, image_code_id):
        # 两个值,第一个是验证码的内容,第二个是图片的二进制
        text, image = captcha.generate_captcha()

        # 建立连接,设置保存到数据库的有效期
        redis_conn = get_redis_connection("code")
        redis_conn.setex("img_%s" %image_code_id, IMAGE_CODE_EXPIRE, text)

        return HttpResponse(image, content_type="image/jpeg")



class VerificationSmsCodeAPIView(APIView):
    """
    当用户点击发送短信验证码的时候,传过来的值为:手机号,图片验证码的内容,以及uuid(image_code_id)
    请求路径:   GET    /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx
    """
    def get(self, request, mobile):

        # 校验参数
        serilizer = VerificationSmsCodeSerializer(data=request.query_params)
        serilizer.is_valid(raise_exception=True)
        redis_conn = get_redis_connection("code")

        # 生成短信验证码
        sms_code = '%06d'%randint(0,999999)
        redis_conn.setex("sms_%s" %mobile, SMS_CODE_EXPRIE, sms_code)

        # 发送短信验证码
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        return Response({'message': "OK"})








